package com.qfedu.sca.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.qfedu.sca.common.param.UserAdd;
import com.qfedu.sca.common.param.UserLogin;
import com.qfedu.sca.common.vo.R;
import com.qfedu.sca.feign.UserService;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Random;

/**
 * 千锋Java,为你而生！
 *
 * @Author: Feri
 * @Date:2024/11/8 10:10
 * @Modified:
 */
@RestController
@RequestMapping("api/user")
@Tag(name = "用户模块")
public class UserController {
    @Resource
    private UserService service;

    @PostMapping("add")
    public R add(@RequestBody UserAdd user){
        return service.add(user);
    }

    //设置熔断降级
    @SentinelResource(value = "userAll",fallback = "allError")
    @GetMapping("all")
    public R all(String name){
        if(new Random().nextBoolean()){
            //模拟 出现 故障
            System.err.println(1/0);
        }

        return service.all(name);
    }
    //降级方法 一旦 all方法出现异常，会自动执行这个方法
    public R allError(String name,Throwable throwable){
        System.err.println("降级方法执行，自动触发熔断");
        System.err.println("异常："+throwable.getMessage());

        return R.fail("亲，网络异常，稍后再来！");
    }
    @PostMapping("login")
    public R login(@RequestBody UserLogin user){
        return service.login(user);
    }

    @GetMapping("logout")
    public R logout(HttpServletRequest request){
        return service.logout();
    }


}
